<template>
	<view style="height: 100vh;background-color: #f2f5f9;">
		<tn-nav-bar bgClass="bg-gradual-blue">搜索蓝牙</tn-nav-bar>
		<view :style="{paddingTop: vuex_custom_bar_height + 'px'}">
			<tn-sticky :offsetTop="0" :customNavHeight="vuex_custom_bar_height">
				<tn-list-cell padding="10px">
					<view class="list-icon-text">
						<view class="list__left">
							<view class="list__left__text">关键字：</view>
						</view>
						<view class="list__right tn-flex tn-flex-wrap">
							<tn-input class="tn-flex-basic-lg" style="width: 60%;" border placeholder="搜索蓝牙名称"
								v-model="keywords" />
							<view class="tn-flex-basic-sm tn-flex tn-flex-col-center tn-flex-row-around"
								v-if="bleVersion!=2">
								<text>版本筛选</text>
								<tn-switch v-model="isFilter" shape="square"></tn-switch>
							</view>
						</view>
					</view>
				</tn-list-cell>
			</tn-sticky>
			<view
				class="cu-list menu card-menu margin-top-lg margin-bottom-xxl shadow-shop bg-white text-black my-radius sm-border">
				<view class="cu-item margin-tb-sm" v-for="(item,index) in list" :key='index' @click="conn(item)">
					<view class="action margin-right-sm">
						<image style="width: 30px;height: 30px" mode='aspectFit' :src="getIcon(item.RSSI)"></image>
					</view>
					<view class='content' style="align-items:start">
						<view class="text-xl" style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
							{{item.name}}
						</view>
						<view class="text-sm"
							style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap;margin-top: 5px;">
							<text class="text-bold"> Mac：</text>{{item.mac}}
							<text class="text-bold margin-left"> 信号强度：</text>{{item.RSSI}}dBm
						</view>
					</view>
				</view>
			</view>
		</view>
		<view style="height: 16vh;"></view>
		<view class="buttons">
			<view class="search" @click="search()">{{isSearch?'停止搜索':'开始搜索'}}</view>
		</view>
	</view>

</template>
<script>
	import BLE from "@/libs/bluetooth/BLE.js";

	import store from '@/store/index.js'
	import xh1 from '@/static/img/xh/wifi_0.png'
	import xh2 from '@/static/img/xh/wifi_1.png'
	import xh3 from '@/static/img/xh/wifi_2.png'
	import xh4 from '@/static/img/xh/wifi_3.png'
	import xh5 from '@/static/img/xh/wifi_4.png'
	var searchInterval = null; //定时器
	export default {
		data() {
			return {
				list: [],
				isFilter: true,
				isSearch: false,
				language: {},
				isIOS: false,
				keywords: '',
				bleVersion: 0,
			}
		},
		watch: {
			isFilter(newVal, oldVal) {
				uni.closeBluetoothAdapter();
				this.isFilter = newVal;
				this.$nextTick(() => {
					this.list = [];
					BLE.Init();
					setTimeout(() => {
						startSearch(this);
					}, 200)
				})
			}
		},
		onShow() {
			if (getApp().globalData.bleObj.state) {
				BLE.Close()
			}
		},
		onLoad(options) {
			let system = uni.getSystemInfoSync().platform;
			if (system === 'android') {
				this.isIOS = false;
			} else {
				this.isIOS = true;
			}
			if (options.v) {
				getApp().globalData.bleVersion = options.v
				this.bleVersion = options.v * 1
				if (options.v * 1 === 2) {
					this.isFilter = false
				}
			}

			uni.closeBluetoothAdapter();

			var that = this;
			// #ifdef MP-WEIXIN
			this.$nextTick(() => {
				this.list = [];
				BLE.Init();
				setTimeout(() => {
					startSearch(this);
				}, 200)
			})
			// #endif
		},
		onUnload() {
			var that = this;
			if (that.isSearch) {
				stopSearch(that);
			}
		},
		onHide() {
			this.list = []
			var that = this;
			if (that.isSearch) {
				stopSearch(that);
			}
		},
		methods: {
			search() {
				var that = this;
				if (that.isSearch) {
					stopSearch(that);
				} else {
					startSearch(that);
				}
			},
			conn(item) {
				var that = this;
				var flag = that.isSearch;
				if (flag) {
					stopSearch(that);
				}
				BLE.confirm(`确认连接 ${item.name} 此设备吗？`, function() {
					BLE.Connect(item.deviceId, function() {
						let bleVersion = getApp().globalData.bleVersion
						if (!bleVersion || bleVersion * 1 < 0) {
							uni.showToast({
								icon: 'none',
								title: '未选择版本信息'
							})
						} else {
							console.log('name', item.name);
							getApp().globalData.bleObj.MAC = item.mac
							getApp().globalData.bleObj.name = item.name

							store.commit('$tStore', {
								name: 'vuex_ble_name',
								value: item.name
							})
							store.commit('$tStore', {
								name: 'vuex_ble_id',
								value: item.deviceId
							})

							uni.showToast({
								icon: 'none',
								title: '连接成功'
							})
							setTimeout(() => {
								if (bleVersion * 1 === 1) {
									uni.reLaunch({
										url: '/pages_ble/ble/tianyi?name=' + item.name
									})
								} else if (bleVersion * 1 === 2) {
									uni.reLaunch({
										url: '/pages_ble/ble/superpower?name=' + item.name
									})
								} else if (bleVersion * 1 === 3) {
									uni.reLaunch({
										url: '/pages_ble/ble/jiabaida?name=' + item.name
									})
								}
							}, 500)
						}
					});
				});
			},
			getIcon(val) {
				if (val * -1 > 90) {
					return xh1
				}
				if (val * -1 > 80) {
					return xh2
				}
				if (val * -1 > 75) {
					return xh3
				}
				if (val * -1 > 65) {
					return xh4
				}
				if (val * -1 > 55) {
					return xh5
				}
				return xh5
			},
		},

	}


	/**
	 * 开启蓝牙搜索
	 * @param {Object} that
	 */
	function startSearch(that) {
		const bleVersion = getApp().globalData.bleVersion;
		var serviceId = []; // getApp().globalData.bleObj.serviceUUID;
		if (that.isFilter) {
			if (bleVersion * 1 === 1) {
				serviceId = ['0000FFF0-0000-1000-8000-00805F9B34FB']
			}
			if (bleVersion * 1 === 2) {
				serviceId = []
			}
			if (bleVersion * 1 === 3) {
				serviceId = ['0000FF00-0000-1000-8000-00805F9B34FB']
			}
			// #ifdef MP-WEIXIN
			uni.startBluetoothDevicesDiscovery({
				services: serviceId,
				allowDuplicatesKey: false,
				interval: 0,
				success: function(res) {
					console.log('startBluetoothDevicesDiscovery', res);
					if (res) {
						if (res.errCode == 0 || res.errno == 0) {
							that.isSearch = true;
							getDevices(that);
						} else {
							BLE.ErrorCode(res, '搜索success');
						}
					}
				},
				fail: function(res) {
					console.log(res, '搜索fail')
					BLE.ErrorCode(res, '搜索fail');
				}
			});
			// #endif
		} else {
			// #ifdef MP-WEIXIN
			uni.startBluetoothDevicesDiscovery({
				allowDuplicatesKey: false,
				interval: 0,
				success: function(res) {
					console.log('startBluetoothDevicesDiscovery', res);
					if (res) {
						if (res.errCode == 0 || res.errno == 0) {
							that.isSearch = true;
							getDevices(that);
						} else {
							BLE.ErrorCode(res, '搜索success');
						}
					}
				},
				fail: function(res) {
					console.log(res, '搜索fail')
					BLE.ErrorCode(res, '搜索fail');
				}
			});
			// #endif
		}
		console.log('serviceId', serviceId);

	}


	/**
	 * 停止蓝牙搜索
	 * @param {Object} that
	 */
	function stopSearch(that) {
		// #ifdef MP-WEIXIN
		uni.stopBluetoothDevicesDiscovery({
			success: function(res) {
				console.log(res);
				if (res) {
					if (res.errCode == 0 || res.errno == 0) {
						that.isSearch = false;
					} else {
						BLE.ErrorCode(res, '停止搜索success');
					}
				}
			},
			fail: function(res) {
				console.log(res, '停止fail');
				BLE.ErrorCode(res, '停止搜索fail');
			}
		});
		// #endif
		clearInterval(searchInterval);
		searchInterval = null;
	}


	/**
	 * 解析蓝牙信息
	 * @param {Object} that
	 */
	function getDevices(that) {
		if (searchInterval != null) {
			clearInterval(searchInterval);
			searchInterval = null;
		}
		searchInterval = setInterval(function() {
			uni.getBluetoothDevices({
				success: function(res) {
					if (res) {
						var devices = res.devices;
						that.list = [];
						for (var i = 0; i < devices.length; i++) {
							var item = devices[i];
							if (!item.localName) {
								continue
							}
							let mac = '';
							if (item.advertisData) {
								let bf = item.advertisData;
								mac = Array.prototype.map.call(new Uint8Array(bf), x => ('00' + x
									.toString(16)).slice(-2)).join(':');
								mac = mac.toUpperCase().substr(12, mac.length)
							}
							if (item.deviceId.indexOf(':') > -1 || !that.isIOS) {
								mac = item.deviceId
							}
							var listitem = {
								RSSI: item.RSSI,
								mac: mac,
								name: item.name.replaceAll(' ', ''),
								deviceId: item.deviceId,
							};

							var keywords = that.keywords;
							if (keywords != undefined && keywords != '' &&
								keywords != null) {
								var itemName = item.name.toLowerCase();
								var macName = item.mac ? item.mac.toLowerCase() : '';
								var tempKey = keywords.toLowerCase();
								if (itemName.indexOf(tempKey) > -1 || macName.indexOf(tempKey) > -1) {
									that.list.push(listitem);
								}
							} else {
								that.list.push(listitem);
							}

						}
					}
				},
				fail: function(res) {
					if (res.errCode == 10000) {
						BLE.Init(function() {});
					} else {
						BLE.ErrorCode(res, '获取已连接的设备fail');
					}
				}
			});
		}, 500);
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #FFFFFF;
	}

	.list__options {
		display: flex;
		align-items: center;
		justify-content: space-evenly;
	}

	.list {
		&__left {
			width: 16%;
			display: flex;
			align-items: center;
			justify-content: center;

			&__icon,
			&__image {
				margin-right: 18rpx;
			}
		}

		&__right {
			width: 84%;
			display: flex;
			align-items: center;
		}
	}

	.list-icon-text,
	.list-image-text {
		display: flex;
		align-items: center;
		justify-content: space-around;
	}

	.list-image-text {
		.list {
			&__left {
				&__image {
					width: 20rpx;
					height: 20rpx;
				}
			}
		}
	}


	.buttons {
		width: 100%;
		position: fixed;
		bottom: 20rpx;
	}

	.buttons .search {
		width: 690rpx;
		height: 80rpx;
		font-weight: 700;
		line-height: 80rpx;
		font-size: 36rpx;
		text-align: center;
		background-color: $tn-main-color;
		margin: 0 auto 10rpx;
		color: #FFFFFF;
		border-radius: 10rpx;
	}
</style>
